<?php
class MainSingleton { 
  private static $instances = array(); 
  private static function get_called_class() {
    $t = debug_backtrace();
//    print_r($t);
//    echo count($t);
    return $t[count($t)-1]["class"];
  }  

  public static function getInstance() { 
    $class = self::get_called_class();
    if(!isset(self::$instances[$class]) ) { 
      self::$instances[$class] = new $class; 
    } 
    return self::$instances[$class]; 
  } 

}

class Singleton extends MainSingleton { 
  public static function getInstance()
  {
    return parent::getInstance();
  }     
  protected function __construct() { 
//    echo "A". PHP_EOL; 
  } 

  protected function __clone() {} 

  public function test() { 
    echo " * test called * "; 
  } 
} 

//Singleton::getInstance()->test();
//Singleton::getInstance()->test();

class Foo
{
    static $instance = array();
    
    static function get_instance()
    {
        if(is_null(self::$instance))
        {
            $class = get_called_class();  
            echo $class;
            self::$instance = new $class();
        }
        $class = get_called_class();
        if(!isset (self::$instance[$class]))
        {
            self::$instance[$class] = new $class();
        }
        return self::$instance[$class];
    }
    
    static function test()
    {
        echo get_called_class();
    }
}

$foo = Foo::get_instance();

class Bar extends Foo
{    
    static function  get_instance()
    {
        return parent::get_instance();        
    }
}


$bar = Bar::get_instance();

var_dump($foo);
echo "<br />";
var_dump($bar);

?>
